// 借用申请页面
const apiService = require('../../../js/services/api/sharedDatabaseService');

Page({
  data: {
    itemDetail: null,
    loading: true
  },

  onLoad: function (options) {
    const itemId = options.id;
    if (itemId) {
      this.loadItemDetail(itemId);
    }
  },

  /**
   * 加载物品详情
   */
  async loadItemDetail(itemId) {
    try {
      this.setData({ loading: true });
      
      // 从API获取物品详情
      const result = await apiService.getIdleItemDetail(itemId);
      if (result?.data) {
        this.setData({
          itemDetail: result.data,
          loading: false
        });
      } else {
        // 如果API失败，使用模拟数据
        this.loadMockItemDetail(itemId);
      }
    } catch (error) {
      console.log('API请求失败，使用模拟数据:', error);
      this.loadMockItemDetail(itemId);
    }
  },

  /**
   * 加载模拟物品详情
   */
  loadMockItemDetail(itemId) {
    const mockItems = [
      {
        id: 1,
        itemName: '电钻套装',
        itemCategory: '工具',
        itemDesc: '包含各种钻头,适合家庭DIY',
        borrowDuration: 30,
        contactInfo: '138****1234',
        borrowCondition: '需要押金200元，使用后归还',
        deposit: 200.00,
        status: 'approved',
        createTime: '2025-08-01T15:02:04.000Z'
      },
      {
        id: 2,
        itemName: '折叠梯',
        itemCategory: '工具',
        itemDesc: '3米高,承重150kg',
        borrowDuration: 7,
        contactInfo: '139****5678',
        borrowCondition: '需要押金100元，使用后归还',
        deposit: 100.00,
        status: 'approved',
        createTime: '2025-08-01T08:30:00.000Z'
      },
      {
        id: 3,
        itemName: '吸尘器',
        itemCategory: '电器',
        itemDesc: '无线吸尘器，续航30分钟',
        borrowDuration: 5,
        contactInfo: '137****9012',
        borrowCondition: '需要押金300元',
        deposit: 300.00,
        status: 'approved',
        createTime: '2025-08-01T09:15:00.000Z'
      }
    ];

    const item = mockItems.find(item => item.id == itemId) || mockItems[0];
    this.setData({
      itemDetail: item,
      loading: false
    });
  },

  /**
   * 提交借用申请
   */
  submitBorrowRequest() {
    if (!this.data.itemDetail) {
      wx.showToast({
        title: '物品信息不存在',
        icon: 'none'
      });
      return;
    }

    wx.showModal({
      title: '确认借用',
      content: `确定要借用"${this.data.itemDetail.itemName}"吗？\n借用时长：${this.data.itemDetail.borrowDuration}天\n押金：${this.data.itemDetail.deposit}元`,
      success: (res) => {
        if (res.confirm) {
          this.createBorrowRequest();
        }
      }
    });
  },

  /**
   * 创建借用请求
   */
  async createBorrowRequest() {
    try {
      wx.showLoading({ title: '提交中...' });
      
      const requestData = {
        itemId: this.data.itemDetail.id,
        itemName: this.data.itemDetail.itemName,
        borrowDuration: this.data.itemDetail.borrowDuration,
        deposit: this.data.itemDetail.deposit,
        contactInfo: this.data.itemDetail.contactInfo,
        status: 'pending'
      };

      const result = await apiService.createBorrowRequest(requestData);
      
      wx.hideLoading();
      
      if (result?.success) {
        wx.showToast({
          title: '申请提交成功',
          icon: 'success'
        });
        
        // 延迟返回上一页
        setTimeout(() => {
          wx.navigateBack();
        }, 1500);
      } else {
        wx.showToast({
          title: '申请提交失败',
          icon: 'none'
        });
      }
    } catch (error) {
      wx.hideLoading();
      console.error('提交借用申请失败:', error);
      wx.showToast({
        title: '申请提交失败',
        icon: 'none'
      });
    }
  },

  /**
   * 联系物主
   */
  contactOwner() {
    if (!this.data.itemDetail?.contactInfo) {
      wx.showToast({
        title: '联系信息不存在',
        icon: 'none'
      });
      return;
    }

    wx.showModal({
      title: '联系物主',
      content: `确定要联系物主吗？\n联系方式：${this.data.itemDetail.contactInfo}`,
      success: (res) => {
        if (res.confirm) {
          wx.makePhoneCall({
            phoneNumber: this.data.itemDetail.contactInfo.replace(/\*+/g, ''),
            fail: (err) => {
              console.error('拨打电话失败:', err);
              wx.showToast({
                title: '拨打失败，请稍后重试',
                icon: 'none'
              });
            }
          });
        }
      }
    });
  },

  /**
   * 格式化时间
   */
  formatTime(timeString) {
    if (!timeString) return '';
    const date = new Date(timeString);
    return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`;
  },

  /**
   * 返回上一页
   */
  goBack() {
    wx.navigateBack();
  }
}); 